﻿using System;
using System.Text;
using System.Drawing;
using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;

public static partial class glDRIVE
{
    /*
    函数 gl.maxn
    n维极值连分式法
    f计算目标函数值与各偏导数值的函数名。
    int maxn(int n, double x[], double eps, double (*f)(double [],int,int))
    参数 n: 自变量个数。
    参数 x: x[n]存放极值点初值。返回极值点。
    参数 eps: 控制精度要求。
    返回值 函数返回标志值。若>0为极大值点；若<0为极小值点;若=0为鞍点。
    */

    public static unsafe string drive_maxn()
    {
        int k = 0, j;
        double eps;
        double[] x = new double[3];

        eps = 0.000001;
        x[0] = 0.0;
        x[1] = 0.0;

        gl.f_xa_nj = maxnf;
        k = gl.maxn(2, x, eps);

        string rs = "";
        rs += gl.html_table("点:", x);
        rs += gl.html_table("k,极值", new double[] { k, maxnf(DPTR(x), 2, 0) });
        return rs;

        /*
        cout <<"点 :" <<endl;
        for (j = 0; j <= 1; j++)
            cout <<"x(" <<j <<") = " <<x[j] <<endl;
        if (k == 0) cout <<"为鞍点" <<endl;
        else if (k > 0) cout <<"为极大值点" <<endl;
        else cout <<"为极小值点" <<endl;
        cout <<"极值 = " <<maxnf(x,2,0) <<endl;
        return "error: 0";
        */
    }

    // 计算目标函数值与各偏导数值
    private static unsafe double maxnf(double* x, int n, int j)
    {
        double y = 0.0;
        //n=n;
        switch (j)
        {
            case 0:
                y = (x[0] - 1.0) * (x[0] - 10.0) + (x[1] + 2.0) * (x[1] + 2.0) + 2.0;
                break;
            case 1:
                y = 2.0 * (x[0] - 1.0);
                break;
            case 2:
                y = 2.0 * (x[1] + 2.0);
                break;
            default:
                break;
        }
        return (y);
    }
}